﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.Common.BLL;
using Yipusoft.Common.Model;
using Yipusoft.Task.BLL;
using Yipusoft.Task.Model;
using System.Text;
using System.Data;


public partial class Task_UserTasksSquadron : System.Web.UI.Page
{
    //设置每页行数
    private int pageSize = 10;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            StartDate.Text = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToShortDateString();
            EndDate.Text = DateTime.Now.ToShortDateString();
            BindUnit();

            BindGrid(0);

            ListPageContral1.SetFirstPage();
            BindGrid2(0);
        }
    }

    void BindUnit()
    {
        string departmentid = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;

        if (departmentid.Substring(0, 4) == "1300")
        {
            //总队
            ddlUnit.Visible = false;
        }
        else if (departmentid.Substring(0, 4) != "1300" && departmentid.Substring(4, 1) == "0")
        {
            //支队
            string key = departmentid.Substring(5, 1);//司政后防
            ddlUnit.DataSource = Department.GetList(" departmentid like '13000" + key + "_' ");
            ddlUnit.DataBind();
        }
        else
        {
            //大中队

            string key = departmentid.Substring(0, 4);
            ddlUnit.DataSource = Department.GetList(" departmentid like '" + key + "0_0'");
            ddlUnit.DataBind();
        }
    }

    private void BindGrid(int pageIndex)
    {
        string departmentid = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;

        string departmentFilter = "";
        if (departmentid.Substring(0, 4) == "1300")
        {
            //总队

        }
        else if (departmentid.Substring(0, 4) != "1300" && departmentid.Substring(4, 1) == "0")
        {
            //支队
            if (ddlUnit.SelectedValue.Substring(6, 1) == "0")
            {
                departmentFilter = "CreateDepartment like '" + ddlUnit.SelectedValue.Substring(0, 6) + "%'";
            }
            else
            {
                departmentFilter = "CreateDepartment ='" + ddlUnit.SelectedValue + "'";
            }
        }
        else
        {
            //大中队
            if (ddlUnit.SelectedValue.Substring(4, 3) == "000")
            {
                departmentFilter = "CreateDepartment like '" + ddlUnit.SelectedValue.Substring(0, 4) + "%'";
            }
            else
            {
                departmentFilter = "CreateDepartment like '" + ddlUnit.SelectedValue.Substring(0, 6) + "%'";
            }
        }

        ViewState["PageIndex"] = pageIndex;
        StringBuilder selectCommandText = new StringBuilder();
        selectCommandText.Append("select * from view_taskusers1 where ParentId=0 and UserID='" + departmentid + "'");
        selectCommandText.Append(" and ((StartDate>='" + StartDate.Text + "' and StartDate<='" + EndDate.Text + "')");
        selectCommandText.Append(" or (EndDate>'" + StartDate.Text + "' and EndDate<='" + EndDate.Text + "'))");

        if (departmentFilter != "")
        {
            selectCommandText.Append(" and  " + departmentFilter);
        }
        //未上报的
        selectCommandText.Append(" and ((taskid not in (select taskid from tasklogs where UserID='" + departmentid + "')  and child=0)");
        //获取子任务的任务列表
        string where = " child<>0 and ((StartDate>='" + StartDate.Text + "' and StartDate<='" + EndDate.Text + "')  or (EndDate>'" + StartDate.Text + "' and EndDate<='" + EndDate.Text + "'))";
        if (departmentFilter != "")
        {
            where += " and " + departmentFilter;
        }

        List<int> nofinishtaskids = GetNotFinish(where, departmentid);
        string nofinishtask = "";
        foreach (int id in nofinishtaskids)
        {
            nofinishtask += id + ",";
        }
        nofinishtask += "0";
        selectCommandText.Append(" or taskid in (" + nofinishtask + ") )");

        UserGrid.DataSource = SplitPage.GetPageData(selectCommandText.ToString(), (int)ViewState["PageIndex"], pageSize);
        UserGrid.DataBind();

        int totalCount = SplitPage.GetRowCount(selectCommandText.ToString(), (int)ViewState["PageIndex"], pageSize);
        ViewState["PageCount"] = SplitPage.GetPageCount(selectCommandText.ToString(), (int)ViewState["PageIndex"], pageSize);
        lbGridInfo.Text = "共有<b>" + totalCount.ToString() + "</b>条记录 第<b>" + ViewState["PageIndex"].ToString() + "</b>页 共<b>" + ViewState["PageCount"].ToString() + "</b>页 每页<b>" + pageSize.ToString() + "</b>条";
        this.btnFirst.Enabled = (int)ViewState["PageIndex"] > 1;
        this.btnPrev.Enabled = (int)ViewState["PageIndex"] > 1;
        this.btnNext.Enabled = (int)ViewState["PageIndex"] < (int)ViewState["PageCount"];
        this.btnLast.Enabled = (int)ViewState["PageIndex"] < (int)ViewState["PageCount"];
    }
    protected void btnFirst_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = 1;
        BindGrid((int)ViewState["PageIndex"]);
    }
    protected void btnPrev_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageIndex"] - 1;
        BindGrid((int)ViewState["PageIndex"]);
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageIndex"] + 1;
        BindGrid((int)ViewState["PageIndex"]);
    }
    protected void btnLast_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageCount"];
        BindGrid((int)ViewState["PageIndex"]);
    }
    protected void UserGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label ID = (Label)e.Row.FindControl("ID");
            ID.Text = (((int)ViewState["PageIndex"]) * pageSize + (e.Row.RowIndex + 1)).ToString();
            LinkButton ButtonLock = (LinkButton)e.Row.FindControl("ButtonLock");
            ButtonLock.Attributes.Add("onclick", "return confirm('" + ButtonLock.Text + "任务后将不能再进行工作汇报，确定吗？')");

            DataRowView dv = e.Row.DataItem as System.Data.DataRowView;
            GridView gv = sender as GridView;
            if (gv.ID == "GridView1")
            {
                Label lbSorce = e.Row.FindControl("lbSorce") as Label;


                if (!Convert.ToBoolean(dv["Evaluated"]))
                {
                    lbSorce.Text = "未审核";
                    lbSorce.ForeColor = System.Drawing.Color.YellowGreen;
                }
                else
                {
                    int score = Convert.ToInt32(dv["Score"]);
                    lbSorce.Text = "得分：" + score;
                    lbSorce.ForeColor = System.Drawing.Color.Tomato;
                }
            }
            else
            {
                HyperLink Title = e.Row.FindControl("Title") as HyperLink;
                DateTime endDate = Convert.ToDateTime(dv["endDate"]);
                if (endDate < DateTime.Now.Date)
                {
                    Title.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
    }
    protected void UserGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridView UserGrid = sender as GridView;
        int taskId = (int)UserGrid.DataKeys[e.NewSelectedIndex].Values[0];
        string userId = (string)UserGrid.DataKeys[e.NewSelectedIndex].Values[1];
        TaskUser.Lock(taskId, userId, true);
        BindGrid((int)ViewState["PageIndex"]);
        BindGrid2(ListPageContral1.CurrentPageIndex);
    }
    private void BindJumpList()
    {
        JumpList.Items.Clear();
        ListItem li;
        for (int i = 0; i < (int)ViewState["PageCount"]; i++)
        {
            li = new ListItem();
            li.Text = (i + 1).ToString();
            li.Value = i.ToString();
            JumpList.Items.Add(li);
        }
        JumpList.SelectedIndex = JumpList.Items.IndexOf(JumpList.Items.FindByValue(ViewState["PageIndex"].ToString()));
    }
    protected void JumpList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGrid(int.Parse(JumpList.SelectedValue));
    }
    public string GetDepartmentName(string departmentId)
    {
        return Department.GetDepartment(departmentId).ShortName + "&nbsp; &nbsp;" + ((DateTime)Eval("startDate")).ToString("MM.dd") + "至" + ((DateTime)Eval("endDate")).ToString("MM.dd");

    }
    public string GetTaskTypeName(int taskType)
    {
        return TaskType.GetTaskType(taskType).TypeName.Substring(0, 1);
    }
    public string GetTitle(string title)
    {
        return title.Length > 24 ? title.Substring(0, 24) + "..." : title;
    }
    public string GetLockText(bool locked)
    {
        return locked ? "解锁" : "锁定";
    }
    protected void ButtonSearch_Click(object sender, EventArgs e)
    {
        BindGrid(0);
        ListPageContral1.SetFirstPage();
        BindGrid2(0);
    }

    protected void ListPageContral1_PageSizeChange(int pageSize, int PageIndex)
    {
        BindGrid2(PageIndex);
    }

    private void BindGrid2(int pageIndex)
    {
        string departmentid = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        string departmentFilter = "";
        if (departmentid.Substring(0, 4) == "1300")
        {
            //总队

        }
        else if (departmentid.Substring(0, 4) != "1300" && departmentid.Substring(4, 1) == "0")
        {
            //支队
            if (ddlUnit.SelectedValue.Substring(6, 1) == "0")
            {
                departmentFilter = "CreateDepartment like '" + ddlUnit.SelectedValue.Substring(0, 6) + "%'";
            }
            else
            {
                departmentFilter = "CreateDepartment ='" + ddlUnit.SelectedValue + "'";
            }
        }
        else
        {
            //大中队
            if (ddlUnit.SelectedValue.Substring(4, 3) == "000")
            {
                departmentFilter = "CreateDepartment like '" + ddlUnit.SelectedValue.Substring(0, 4) + "%'";
            }
            else
            {
                departmentFilter = "CreateDepartment like '" + ddlUnit.SelectedValue.Substring(0, 6) + "%'";
            }
        }
        ViewState["PageIndex"] = pageIndex;

        StringBuilder selectCommandText = new StringBuilder();
        selectCommandText.Append("select * from view_taskusers1 where ParentId=0 and UserID='" + departmentid + "'");
        selectCommandText.Append(" and ((StartDate>='" + StartDate.Text + "' and StartDate<='" + EndDate.Text + "')");
        selectCommandText.Append(" or (EndDate>'" + StartDate.Text + "' and EndDate<='" + EndDate.Text + "'))");

        if (departmentFilter != "")
        {
            selectCommandText.Append(" and  " + departmentFilter);
        }
        //上报的
        selectCommandText.Append(" and ((taskid in (select taskid from tasklogs where UserID='" + departmentid + "') and child=0  or Evaluated=1)");
        //获取子任务的任务列表
        string where = " child<>0 and ((StartDate>='" + StartDate.Text + "' and StartDate<='" + EndDate.Text + "')  or (EndDate>'" + StartDate.Text + "' and EndDate<='" + EndDate.Text + "'))";

        if (departmentFilter != "")
        {
            where += " and " + departmentFilter;
        }

        List<int> nofinishtaskids = GetFinish(where, departmentid);
        string nofinishtask = "";
        foreach (int id in nofinishtaskids)
        {
            nofinishtask += id + ",";
        }
        nofinishtask += "0";
        selectCommandText.Append(" or taskid in (" + nofinishtask + ") )");

        int totalCount = SplitPage.GetRowCount(selectCommandText.ToString(), (int)ViewState["PageIndex"], pageSize);
        ListPageContral1.ItemCount = totalCount;

        GridView1.DataSource = SplitPage.GetPageData(selectCommandText.ToString(), pageIndex, ListPageContral1.PageSize);
        GridView1.DataBind();
    }

    List<int> GetNotFinish(string Where, string Userid)
    {
        List<int> NoTaskids = new List<int>();
        DataTable dt = SplitPage.ExecuteSQL("select taskid from tasks where " + Where).Tables[0];
        foreach (DataRow dr in dt.Rows)
        {
            bool isFinish = true;
            int taskid = Convert.ToInt32(dr[0]);
            List<string> taskids = new List<string>();
            string sql = "select taskid from tasklogs where taskid in(select taskid from tasks where parentid='" + taskid + "') and userid='" + Userid + "'";
            DataTable userdt = SplitPage.ExecuteSQL(sql).Tables[0];
            foreach (DataRow userdr in userdt.Rows)
            {
                taskids.Add(userdr[0].ToString());
            }

            List<TaskInfo> tasks = Task.GetTasks(taskid);

            for (int i = 1; i < tasks.Count; i++)
            {
                if (!taskids.Contains(tasks[i].TaskId.ToString()))
                {
                    isFinish = false;
                    break;
                }
            }

            if (!isFinish)
            {
                NoTaskids.Add(taskid);
            }
        }
        return NoTaskids;
    }

    List<int> GetFinish(string Where, string Userid)
    {
        List<int> NoTaskids = new List<int>();
        DataTable dt = SplitPage.ExecuteSQL("select taskid from tasks where " + Where).Tables[0];
        foreach (DataRow dr in dt.Rows)
        {
            bool isFinish = true;
            int taskid = Convert.ToInt32(dr[0]);
            List<string> taskids = new List<string>();
            string sql = "select taskid from tasklogs where taskid in(select taskid from tasks where parentid='" + taskid + "') and userid='" + Userid + "'";
            DataTable userdt = SplitPage.ExecuteSQL(sql).Tables[0];
            foreach (DataRow userdr in userdt.Rows)
            {
                taskids.Add(userdr[0].ToString());
            }

            List<TaskInfo> tasks = Task.GetTasks(taskid);

            for (int i = 1; i < tasks.Count; i++)
            {
                if (!taskids.Contains(tasks[i].TaskId.ToString()))
                {
                    isFinish = false;
                    break;
                }
            }
            if (isFinish)
            {
                NoTaskids.Add(taskid);
            }
        }
        return NoTaskids;
    }
}
